<template>
  <div class="time-chart-container">
    <div class="chart-header">
      <div class="chart-title">学习时间统计图</div>
      <div class="chart-controls">
        <el-select v-model="timeUnit" @change="onTimeUnitChange" placeholder="请选择时间单位" style="width: 80px;">
          <el-option label="日" value="day"></el-option>
          <el-option label="周" value="week"></el-option>
          <el-option label="月" value="month"></el-option>
          <el-option label="年" value="year"></el-option>
        </el-select>
        <el-date-picker
          v-if="timeUnit === 'day'"
          v-model="selectedDate"
          type="date"
          placeholder="请选择日期"
          value-format="YYYY-MM-DD"
          style="width: 150px; margin-left: 10px;"
          @change="updateChart"
        />
        <el-date-picker
          v-else-if="timeUnit === 'week'"
          v-model="selectedWeek"
          type="week"
          format="YYYY-MM-DD"
          placeholder="请选择周"
          style="width: 200px; margin-left: 10px;"
          :first-day-of-week="1"
          value-format="YYYY-MM-DD"
          @change="updateWeekDisplay"
        />
        <span 
          v-if="timeUnit === 'week' && weekDisplayText"
          style="margin-left: 10px; color: #606266; font-size: 14px;"
        >
          {{ weekDisplayText }}
        </span>
        <el-date-picker
          v-else-if="timeUnit === 'month'"
          v-model="selectedMonth"
          type="month"
          placeholder="请选择月"
          value-format="YYYY-MM"
          style="width: 150px; margin-left: 10px;"
          @change="updateChart"
        />
        <el-date-picker
          v-else-if="timeUnit === 'year'"
          v-model="selectedYear"
          type="year"
          placeholder="请选择年"
          value-format="YYYY"
          style="width: 150px; margin-left: 10px;"
          @change="updateChart"
        />
      </div>
    </div>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
import { dayjs } from 'element-plus';
import 'dayjs/locale/zh-cn';

// 设置中文locale
dayjs.locale('zh-cn');

// 定义组件属性
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
});

// 定义响应式变量
const chartContainer = ref(null);
const timeUnit = ref('month'); // 默认按月显示
const selectedDate = ref(''); // 选择的日期
const selectedWeek = ref(''); // 选择的周
const selectedMonth = ref(''); // 选择的月
const selectedYear = ref(''); // 选择的年
const weekDisplayText = ref(''); // 周范围显示文本
let chartInstance = null;

// 初始化图表
onMounted(() => {
  initChart();
  // 初始化时自动填充当前时间
  autoFillCurrentTime();
  updateChart();
});

// 组件卸载前销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});

// 监听数据变化，重新绘制图表
watch(() => props.data, () => {
  updateChart();
});

// 自动填充当前时间
function autoFillCurrentTime() {
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = String(now.getMonth() + 1).padStart(2, '0');
  const currentDate = String(now.getDate()).padStart(2, '0');
  
  switch (timeUnit.value) {
    case 'day':
      selectedDate.value = `${currentYear}-${currentMonth}-${currentDate}`;
      break;
    case 'week':
      // 获取当前周的周一
      const monday = getMonday(now);
      selectedWeek.value = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(monday.getDate()).padStart(2, '0')}`;
      updateWeekDisplay();
      break;
    case 'month':
      selectedMonth.value = `${currentYear}-${currentMonth}`;
      break;
    case 'year':
      selectedYear.value = `${currentYear}`;
      break;
  }
}

// 时间单位变化处理
function onTimeUnitChange() {
  // 重置所有日期选择
  selectedDate.value = '';
  selectedWeek.value = '';
  selectedMonth.value = '';
  selectedYear.value = '';
  weekDisplayText.value = '';
  
  // 自动填充当前时间
  autoFillCurrentTime();
  updateChart();
}

// 处理周选择变化
function updateWeekDisplay() {
  if (selectedWeek.value) {
    // 计算周范围
    const monday = getMonday(new Date(selectedWeek.value));
    const sunday = new Date(monday);
    sunday.setDate(monday.getDate() + 6);
    
    // 格式化日期
    const mondayStr = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(monday.getDate()).padStart(2, '0')}`;
    const sundayStr = `${sunday.getFullYear()}-${String(sunday.getMonth() + 1).padStart(2, '0')}-${String(sunday.getDate()).padStart(2, '0')}`;
    
    weekDisplayText.value = `${mondayStr}至${sundayStr}`;
  } else {
    weekDisplayText.value = '';
  }
  updateChart();
}

// 初始化ECharts实例
function initChart() {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);
  }
}

// 处理窗口大小变化
function handleResize() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

// 更新图表
function updateChart() {
  if (!chartInstance || !props.data.length) return;
  
  // 处理数据
  const processedData = processData(props.data, timeUnit.value);
  
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const date = params[0].axisValue;
        const value = params[0].value;
        let tooltipText = '';
        
        // 根据不同的时间单位显示不同的tooltip
        switch (timeUnit.value) {
          case 'day':
            if (selectedDate.value) {
              tooltipText = `${selectedDate.value} ${date}<br/>学习时长: ${value} 小时`;
            } else {
              tooltipText = `${date}<br/>学习时长: ${value} 小时`;
            }
            break;
          case 'week':
            if (selectedWeek.value) {
              // 显示选定的周范围
              tooltipText = `${weekDisplayText.value} ${date}<br/>学习时长: ${value} 小时`;
            } else {
              tooltipText = `${date}<br/>学习时长: ${value} 小时`;
            }
            break;
          case 'month':
            if (selectedMonth.value) {
              tooltipText = `${selectedMonth.value}-${date}<br/>学习时长: ${value} 小时`;
            } else {
              tooltipText = `${date}<br/>学习时长: ${value} 小时`;
            }
            break;
          case 'year':
            if (selectedYear.value) {
              tooltipText = `${selectedYear.value}年${date}月<br/>学习时长: ${value} 小时`;
            } else {
              tooltipText = `${date}年<br/>学习时长: ${value} 小时`;
            }
            break;
          default:
            tooltipText = `${date}<br/>学习时长: ${value} 小时`;
        }
        
        return tooltipText;
      }
    },
    xAxis: {
      type: 'category',
      data: processedData.map(item => item.date)
    },
    yAxis: {
      type: 'value',
      name: '学习时长 (小时)'
    },
    series: [{
      data: processedData.map(item => item.totalTime / 60), // 转换为小时
      type: 'line',
      smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: 'rgba(58, 132, 217, 0.8)'
          },
          {
            offset: 1,
            color: 'rgba(58, 132, 217, 0.1)'
          }
        ])
      },
      itemStyle: {
        color: '#3a84d9'
      }
    }]
  };
  
  // 设置图表选项
  chartInstance.setOption(option, true);
}

// 处理数据，根据时间单位聚合数据
function processData(rawData, unit) {
  // 创建一个Map来存储每天的总时间
  const timeMap = new Map();
  
  // 过滤数据 based on selected date/week/month/year
  let filteredData = [...rawData];
  
  if (unit === 'day') {
    if (selectedDate.value) {
      filteredData = rawData.filter(item => {
        const itemDate = new Date(item.startTime);
        const selectedDateObj = new Date(selectedDate.value);
        return (
          itemDate.getFullYear() === selectedDateObj.getFullYear() &&
          itemDate.getMonth() === selectedDateObj.getMonth() &&
          itemDate.getDate() === selectedDateObj.getDate()
        );
      });
    }
  } else if (unit === 'week' && selectedWeek.value) {
    // 使用getMonday函数确保周从周一开始
    const monday = getMonday(new Date(selectedWeek.value));
    const sunday = new Date(monday);
    sunday.setDate(monday.getDate() + 6);
    
    filteredData = rawData.filter(item => {
      const itemDate = new Date(item.startTime);
      return itemDate >= monday && itemDate <= sunday;
    });
  } else if (unit === 'month' && selectedMonth.value) {
    const [year, month] = selectedMonth.value.split('-').map(Number);
    filteredData = rawData.filter(item => {
      const itemDate = new Date(item.startTime);
      return (
        itemDate.getFullYear() === year &&
        itemDate.getMonth() === month - 1
      );
    });
  } else if (unit === 'year' && selectedYear.value) {
    const year = Number(selectedYear.value);
    filteredData = rawData.filter(item => {
      const itemDate = new Date(item.startTime);
      return itemDate.getFullYear() === year;
    });
  }
  
  filteredData.forEach(item => {
    // 解析开始时间
    const startTime = new Date(item.startTime);
    let key;
    
    // 根据不同的时间单位生成key
    switch (unit) {
      case 'day':
        // 如果选择了具体日期，显示每小时的数据
        if (selectedDate.value) {
          key = `${String(startTime.getHours()).padStart(2, '0')}:00`;
        } else {
          // 格式化为 "YYYY-MM-DD"
          key = `${startTime.getFullYear()}-${String(startTime.getMonth() + 1).padStart(2, '0')}-${String(startTime.getDate()).padStart(2, '0')}`;
        }
        break;
      case 'week':
        // 显示一周7天的数据
        if (selectedWeek.value) {
          // 获取选定周的周一日期
          const monday = getMonday(new Date(selectedWeek.value));
          // 获取当前数据的周一日期
          const itemMonday = getMonday(startTime);
          // 检查是否在同一周
          if (monday.getTime() === itemMonday.getTime()) {
            // 显示具体日期格式 MM-DD
            key = `${String(startTime.getMonth() + 1).padStart(2, '0')}-${String(startTime.getDate()).padStart(2, '0')}`;
          } else {
            return; // 跳过不在选定周的数据
          }
        } else {
          // 获取周一日期和周日日期
          const monday = getMonday(startTime);
          const sunday = new Date(monday);
          sunday.setDate(monday.getDate() + 6);
          const mondayStr = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(monday.getDate()).padStart(2, '0')}`;
          const sundayStr = `${sunday.getFullYear()}-${String(sunday.getMonth() + 1).padStart(2, '0')}-${String(sunday.getDate()).padStart(2, '0')}`;
          key = `${mondayStr}至${sundayStr}`;
        }
        break;
      case 'month':
        // 如果选择了具体月份，显示每天的数据
        if (selectedMonth.value) {
          const [year, month] = selectedMonth.value.split('-').map(Number);
          if (startTime.getFullYear() === year && startTime.getMonth() === month - 1) {
            key = `${String(startTime.getDate()).padStart(2, '0')}`;
          } else {
            return; // 跳过不在选定月份的数据
          }
        } else {
          // 格式化为 "YYYY-MM"
          key = `${startTime.getFullYear()}-${String(startTime.getMonth() + 1).padStart(2, '0')}`;
        }
        break;
      case 'year':
        // 如果选择了具体年份，显示每月的数据
        if (selectedYear.value) {
          if (startTime.getFullYear() === Number(selectedYear.value)) {
            key = `${String(startTime.getMonth() + 1).padStart(2, '0')}`;
          } else {
            return; // 跳过不在选定年份的数据
          }
        } else {
          key = `${startTime.getFullYear()}`;
        }
        break;
      default:
        key = `${startTime.getFullYear()}-${String(startTime.getMonth() + 1).padStart(2, '0')}-${String(startTime.getDate()).padStart(2, '0')}`;
    }
    
    // 累加时间
    if (timeMap.has(key)) {
      timeMap.set(key, timeMap.get(key) + item.sumTime);
    } else {
      timeMap.set(key, item.sumTime);
    }
  });
  
  // 转换为数组并排序
  const result = Array.from(timeMap, ([date, totalTime]) => ({ date, totalTime }));
  
  // 根据不同的时间单位进行排序
  if (unit === 'day' && selectedDate.value) {
    // 按小时排序 00:00 到 23:00
    result.sort((a, b) => {
      const hourA = parseInt(a.date.split(':')[0]);
      const hourB = parseInt(b.date.split(':')[0]);
      return hourA - hourB;
    });
  } else if (unit === 'week' && selectedWeek.value) {
    // 按日期排序 (MM-DD格式)
    result.sort((a, b) => {
      const [monthA, dayA] = a.date.split('-').map(Number);
      const [monthB, dayB] = b.date.split('-').map(Number);
      return monthA * 100 + dayA - (monthB * 100 + dayB);
    });
  } else if (unit === 'month' && selectedMonth.value) {
    // 按日期排序
    result.sort((a, b) => parseInt(a.date) - parseInt(b.date));
  } else if (unit === 'year' && selectedYear.value) {
    // 按月份排序
    result.sort((a, b) => parseInt(a.date) - parseInt(b.date));
  } else {
    // 默认排序
    result.sort((a, b) => {
      // 处理周范围格式的排序
      if (a.date.includes('至') && b.date.includes('至')) {
        const startDateA = new Date(a.date.split('至')[0]);
        const startDateB = new Date(b.date.split('至')[0]);
        return startDateA - startDateB;
      }
      return new Date(a.date) - new Date(b.date);
    });
  }
  
  return result;
}

// 计算周一日期的辅助函数
function getMonday(d) {
  const date = new Date(d);
  const day = date.getDay();
  const diff = date.getDate() - day + (day === 0 ? -6 : 1); // 调整到周一
  return new Date(date.setDate(diff));
}

// 计算周数的辅助函数
function getWeekNumber(d) {
  // 复制日期避免修改原日期
  const date = new Date(d.getTime());
  date.setHours(0, 0, 0, 0);
  // 设置为周一
  date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
  // 1月4日所在的周是第一周
  const week1 = new Date(date.getFullYear(), 0, 4);
  // 调整为周一
  week1.setDate(week1.getDate() + 3 - (week1.getDay() + 6) % 7);
  // 计算周数
  const weekNumber = 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
  return weekNumber;
}
</script>

<style scoped>
.time-chart-container {
  width: 100%;
  height: 400px;
  padding: 0px;
  box-sizing: border-box;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #5c5e62;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: calc(100% - 60px);
}
</style>